<template>
  <div class="app-box">
    <div class="title-header">换卡申请</div>
    <div class="main-box">
      <div class="main-title">换卡申请</div>
      <div class="main-content">
        <div class="phone-input">
          <Field
            v-model="phoneNumber"
            maxlength="12"
            class="m-input"
            placeholder="请输入登录手机号"
            @change="handleClearIccid"
          />
          <div class="phone-btn" @click="handleSearch">查询</div>
        </div>
        <div class="menu-box">
          <div class="menu-placeholder" v-if="!submitData.iccid">请选择需要更换的卡号</div>
          <DropdownMenu class="menu-inner" active-color="#ff6d41">
            <DropdownItem v-model="submitData.iccid" :options="iccidList.data"> </DropdownItem>
          </DropdownMenu>
        </div>
        <!-- <Field v-model="submitData.iccid" maxlength="12" class="m-input" placeholder="请输入需要更换的卡号" /> -->
        <Field v-model="submitData.receiverName" class="m-input" placeholder="请输入收货人姓名" />
        <Field v-model="submitData.receiverPhone" maxlength="11" class="m-input" placeholder="请输入收货人电话" />
        <Field
          class="m-input"
          readonly
          clickable
          v-model="submitData.provinceName"
          placeholder="选择省"
          @click="showPicker = !showPicker"
        />
        <Field
          class="m-input"
          readonly
          clickable
          v-model="submitData.cityName"
          placeholder="选择市"
          @click="showCityPicker = !showCityPicker"
        />
        <Field
          class="m-input"
          readonly
          clickable
          v-model="submitData.countyName"
          placeholder="选择区/县"
          @click="showCountyPicker = !showCountyPicker"
        />
        <Field v-model="submitData.receiverAddress" class="m-input" placeholder="请输入详细地址" />
        <!-- 省选择器 -->
        <Popup v-model:show="showPicker" position="bottom">
          <Picker :show-toolbar="false" :columns="provinceList.data" @change="onConfirm" :default-index="provinceIdx" />
        </Popup>
        <!-- 市选择器 -->
        <Popup v-model:show="showCityPicker" position="bottom">
          <Picker :show-toolbar="false" :columns="cityList.data" @change="onCityConfirm" :default-index="cityIdx" />
        </Popup>
        <!-- 县选择器 -->
        <Popup v-model:show="showCountyPicker" position="bottom">
          <Picker
            :show-toolbar="false"
            :columns="countyList.data"
            @change="onCountyConfirm"
            :default-index="countyIdx"
          />
        </Popup>
        <div class="recognition-content">
          <Field
            v-model="message"
            class="recognition-ipt"
            type="textarea"
            placeholder="姓名+手机号码+xx省+xx市+xx区或xx镇+xx大街+xxx二号楼xx室"
          />
          <div class="recognition-title" @click="parseAddress">智能识别</div>
        </div>
      </div>
      <div class="submit-btn" @click="handSubmit">提交</div>
    </div>
    <div class="footer-box">
      <div class="footer-item">
        <img src="../assets/icon.png" alt="" />
        包邮
      </div>
      <div class="footer-item">
        <img src="../assets/icon.png" alt="" />
        正品保证
      </div>
      <div class="footer-item">
        <img src="../assets/icon.png" alt="" />
        消费者保障服务
      </div>
    </div>
  </div>
</template>

<script setup>
import { Field, Picker, Popup, Toast, DropdownMenu, DropdownItem } from 'vant';
import { ref, reactive } from 'vue';
import AddressParse from 'address-parse';
import area from '../utils/area.json';
import { parseLocationParams } from '../utils/index';
import { apiAddLinkApply, apiQueryCardList } from '../api';
import { useRouter } from 'vue-router';
const router = useRouter();
let submitFlag = ref(false);
let phoneNumber = ref('');
const submitData = reactive({
  iccid: '',
  receiverName: '',
  receiverPhone: '',
  receiverAddress: '',
  provinceName: '',
  cityName: '',
  countyName: '',
});
let iccidList = reactive({
  data: [],
});
// 省弹出框控件
let showPicker = ref(false);
// 市弹出框控件
let showCityPicker = ref(false);
// 区弹出框控件
let showCountyPicker = ref(false);
// 省份数据
let provinceList = reactive({ data: [] });
provinceList.data = area.map((item) => item.label);
provinceList.data.unshift({ value: '请选择省', text: '请选择省' });
// 市份数据
let cityList = reactive({ data: [] });
// 区份数据
let countyList = reactive({ data: [] });
let provinceIdx = ref();
let cityIdx = ref();
let countyIdx = ref();
let message = ref('');
//  @input="onInput"
// const onInput = (e) => {
//   const regex = /[^a-zA-Z0-9]/g;
//   let value = e.target.value;
//   submitData.receiverAddress = value.replace(regex, '');
// };

const onConfirm = (e) => {
  console.log('e', e);
  showPicker.value = !showPicker.value;
  if (e && e?.text !== '请选择省') {
    submitData.provinceName = e;
    submitData.cityName = '';
    submitData.countyName = '';
    cityIdx.value = 0;
    countyIdx.value = 0;
    if (submitData.provinceName) {
      provinceIdx.value = area.findIndex((item) => item.label === submitData.provinceName) + 1;
      changeSelection();
    }
  }
};
const onCityConfirm = (e) => {
  console.log('e', e, countyList.length);
  showCityPicker.value = !showCityPicker.value;
  if (e?.text !== '请先选择省' && e?.text !== '请选择市') {
    submitData.cityName = e;
    submitData.countyName = '';
    countyIdx.value = 0;
    if (submitData.cityName) {
      // 市下标
      cityIdx.value = area[provinceIdx.value - 1].children.findIndex((item) => item.label === submitData.cityName) + 1;
      changeSelection();
    }
  }
};
const onCountyConfirm = (e) => {
  showCountyPicker.value = !showCountyPicker.value;
  if (e?.text !== '请先选择市' && e?.text !== '请选择区') {
    submitData.countyName = e;
  }
};
// 更改省市地址数据
const changeSelection = () => {
  cityList.data =
    provinceIdx.value !== undefined && submitData.provinceName
      ? area[provinceIdx.value - 1].children.map((i) => i.label)
      : [{ text: '请先选择省', disabled: true }];
  countyList.data =
    cityIdx.value !== undefined && submitData.cityName
      ? area[provinceIdx.value - 1].children[cityIdx.value - 1].children.map((i) => i.label)
      : [{ text: '请先选择市', disabled: true }];
  // if (countyList.data[0].text !== '请先选择市') {
  countyList.data.unshift({ value: '请选择区', text: '请选择区' });
  // } else if (cityList.data[0].text !== '请先选择省') {
  cityList.data.unshift({ value: '请选择市', text: '请选择市' });
  // }
};
changeSelection();
const parseAddress = () => {
  /*判断解析的地址内容不为空*/
  if (message.value != '') {
    const result = AddressParse.parse(message.value);
    let parse = result[0];
    submitData.receiverName = parse.name ? parse.name : submitData.receiverName;
    submitData.receiverPhone = parse.mobile ? parse.mobile : submitData.receiverPhone;
    submitData.receiverAddress = parse.details;
    submitData.provinceName = parse.province;
    submitData.cityName = parse.city;
    submitData.countyName = parse.area;
    // if (submitData.provinceName) {
    //   provinceIdx.value = area.findIndex((item) => item.label.indexOf(submitData.provinceName) !== -1);
    //   cityIdx.value =
    //     area[provinceIdx.value].children &&
    //     area[provinceIdx.value].children.findIndex((item) => item.label === submitData.cityName);
    //   countyIdx.value = (area[provinceIdx.value].children[cityIdx.value].children ?? []).findIndex(
    //     (item) => item.label === submitData.countyName
    //   );
    // }
    // changeSelection();
  } else {
    Toast('请输入您要识别的地址');
  }
};
const handSubmit = async () => {
  if (submitFlag.value) {
    Toast('请勿重复提交...');
    return;
  }
  let location = parseLocationParams(window.location.search);
  let msg = '';
  let phoneReg = /^1\d{10}/;

  if (!submitData.iccid) {
    msg = '请输入卡号';
  } else if (!submitData.receiverName) {
    msg = '请输入收件人姓名';
  } else if (!submitData.receiverPhone) {
    msg = '请输入收件人手机号';
  } else if (!phoneReg.test(submitData.receiverPhone)) {
    msg = '请输入正确的手机号';
  } else if (!submitData.provinceName) {
    msg = '请选择省份';
  } else if (!submitData.cityName) {
    msg = '请选择市';
  } else if (!submitData.countyName) {
    msg = '请选择区';
  } else if (!submitData.receiverAddress) {
    msg = '请输入详细地址';
  }
  if (msg !== '') return Toast(msg);
  submitFlag.value = true;
  try {
    const res = await apiAddLinkApply(Object.assign({}, submitData, location));
    console.log('res', res);
    if (res.code === 200) {
      Toast(res.msg ?? '提交成功');
      let _list = iccidList.data.filter((item) => item.iccid === submitData.iccid);
      router.push({
        path: '/success',
        query: { iccid: submitData.iccid, id: _list[0]?.id ?? '', phone: phoneNumber.value },
      });
      clearSubmitData();
    } else {
      Toast(res.msg ?? '提交失败');
    }
  } catch (error) {
    console.log(error);
  } finally {
    setTimeout(() => {
      submitFlag.value = false;
    }, 2000);
  }
};
const clearSubmitData = () => {
  submitData.iccid = '';
  submitData.receiverName = '';
  submitData.receiverPhone = '';
  submitData.receiverAddress = '';
  submitData.provinceName = '';
  submitData.cityName = '';
  submitData.countyName = '';
  phoneNumber.value = '';
  message.value = '';
  provinceIdx.value = '';
  cityIdx.value = '';
  countyIdx.value = '';
};
const handleClearIccid = () => {
  let phoneReg = /^1\d{10}/;
  if (!phoneReg.test(phoneNumber.value)) {
    submitData.iccid = '';
    iccidList.data = [];
  }
};
// 搜索卡号
const handleSearch = async () => {
  let phoneReg = /^1\d{10}/;
  if (!phoneReg.test(phoneNumber.value)) {
    Toast('请输入正确的手机号');
    return;
  }
  try {
    const res = await apiQueryCardList({ phonenumber: phoneNumber.value });
    if (res.code === 200) {
      let data = res.rows;
      iccidList.data = (data ?? []).map((item) => ({
        value: item.iccid,
        text: item.iccid,
        id: item.id,
        iccid: item.iccid,
      }));
      let item = (data ?? []).filter((item) => item.defaultStatus === 'Y');
      console.log('item', item);
      if (item.length > 0) {
        submitData.iccid = item[0].iccid;
      }
    } else {
      Toast(res.msg ?? '提交失败');
    }
  } catch (error) {
    console.log(error);
  }
};
</script>

<style>
@import '../index.css';
</style>
